package com.imooc.course.system.controller.admin;

import com.imooc.course.system.form.RoleResourceForm;
import com.imooc.course.system.form.PageForm;
import com.imooc.course.server.dto.RoleResourceDto;
import com.imooc.course.server.dto.PageDto;
import com.imooc.course.server.dto.ResponseDto;
import com.imooc.course.server.service.RoleResourceService;
import com.imooc.course.server.utils.CopyUtil;
import com.imooc.course.server.utils.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/admin/roleResource")
public class RoleResourceController {

    private static final Logger log = LoggerFactory.getLogger(RoleResourceController.class);
    public static final String BUSINESS_NAME = "角色资源关联";


    @Resource(name = "roleResourceService")
    private RoleResourceService roleResourceService;

    /**
     * 查询列表
     * @param pageForm 传入的page和size
     * @return
     */
    @PostMapping("/list")
    public ResponseDto getList(@RequestBody PageForm pageForm) {
        PageDto pageDto = CopyUtil.copy(pageForm, PageDto.class);
        roleResourceService.getList(pageDto);
        return ResponseDto.success().setContent(pageDto);
    }

    /**
     * 展示拥有的授权
     * @param id
     * @return
     */
    @GetMapping("/check/node/{id}")
    public ResponseDto checkNode(@PathVariable String id) {
        List<RoleResourceDto> list = roleResourceService.checkNode(id);
        return ResponseDto.success().setContent(list);
    }

    /**
     * 角色获取资源受权
     * @param roleResourceForm
     * @return
     */
    @PostMapping("/authorization")
    public ResponseDto authorization(@RequestBody RoleResourceForm roleResourceForm) {
        roleResourceService.authorization(CopyUtil.copy(roleResourceForm, RoleResourceDto.class));
        return ResponseDto.success();
    }



    /**
     * 保存，id有值为更新，id无值为新增
     * @param roleResourceForm
     * @return
     */
    @PostMapping("/save")
    public ResponseDto addRoleResource(@RequestBody RoleResourceForm roleResourceForm) {
        //入参检查
        ValidatorUtil.notNull(roleResourceForm.getRoleId(), "角色");
        ValidatorUtil.notNull(roleResourceForm.getResourceId(), "资源");

        RoleResourceDto roleResourceDto = CopyUtil.copy(roleResourceForm, RoleResourceDto.class);
        roleResourceService.save(roleResourceDto);
        return ResponseDto.success().setContent(roleResourceDto);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResponseDto del(@PathVariable String id) {
        roleResourceService.delete(id);
        return ResponseDto.success();
    }
}
